;(function($) {
  var comment_functions = {
    load: function(post_id) {

    },
    add_html: function(id,html){
      var type = 0;
      if($('#list_comment' + id).length == 0){
        var htmlRaw = '';
        htmlRaw += '<h6>Comment :</h6>' +
                   '<div id="list_comment'+ id +'" class="list_comment" rel="'+ id +'">' +
                   '</div>' +
                   '<div style="text-align:right;margin-top: 5px;" id="more'+ id +'" >' +
                   '<input type="button" class="btn btn-info" style="" value="+ More" rel="'+ id +'" />' +
                   '</div>';
        $('#comment_content' + id).html(htmlRaw);
               
      }
      if($('#list_comment' + id).children('.row-fluid').length == 1){
        type = 1;
      }      
      $('#list_comment' + id).prepend(html);
      
      show_more.init_one(id,type);      
    },   
    make_html: function(imgUrl,username,user_id,time,content,post_id,comment_id,del_path){
      var html = '';
      html += '<div class="row-fluid" id="comment'+ comment_id +'">' +
      '<div class="span12 well" style="background-color: #E6E6E6;margin:0;">' +
      '<div class="span1">';
      html += '<img src="';
      if($.trim(imgUrl) != ""){
        html += imgUrl;
      }else{
        html += "/data/no-image.jpg";
      }
      html += '" onerror="this.src=\'/data/no-image.jpg\'" class="img-polaroid" alt="" />' +
      '</div>' +
      '<div class="span11">' +
      '<div class="btn-group" style="float:right;">' +
      '<button type="button" class="close" data-pid="'+ post_id +'" data-cid="'+ comment_id +'" data-url="' + del_path + '" style="color:red;">×</button>' +
      '</div>' +
      '<strong><a href="/user/' + user_id + '" target = "_blank">' + username + '</a></strong><br/>' +
      '<span>' + content + '</span>' +
      '<div style="clear:both;"></div>' +
      '<i style="float:right;font-size:10px;">( ' + time + ' )</i>' +
      '</div>' +
      '</div>' +
      '</div>';
      return html;
    },
    del_html: function(pid,cid){
      if($('#list_comment' + pid).children('.row-fluid').length == 1){
        $('#comment_content' + pid).html('');
      }else{
        $('#comment'+cid).remove();
      }
      show_more.init_one(pid);      
    },
    add: function(imgUrl,username,user_id,post_url,post_id,content){
      var comment_txt = $.trim(content);
      if(comment_txt == ''){
        $('#loading'+post_id).hide();
        alert("Don't allow empty content !");
        return false;
      }else{
        if(comment_txt.length > 250 || comment_txt.length < 10){
          $('#loading'+post_id).hide();
          alert("Content must be greater than 10 characters and less than 250 characters");
          return false;
        }
      }

      $.ajax({
        type:"POST",
        url:post_url,
        data:"id=" + post_id + "&content=" + content,
        success:function(res){
          if(res.result == 'Success !'){
            var html = comment_functions.make_html(imgUrl,username,user_id,res.time,content,post_id,res.c_id,res.del_path);
            comment_functions.add_html(post_id,html);
          }else if(res.result == 'Invalid information !'){
            alert('Invalid information !');
          }else{
            alert('Server is busy now. Please try again later !');
          }

          $('#loading'+post_id).hide();
        }
      });
    },
    del: function(post_id,comment_id,post_url){
      $.ajax({
        type:"POST",
        url:post_url,
        data:"pid=" + post_id + "&cid=" + comment_id,
        success:function(res){
          if(res.result == 'Success !'){
            comment_functions.del_html(post_id,comment_id);  
          }else if(res.result == 'Invalid information !'){
            alert('Invalid information !');
          }else{
            alert('Server is busy now. Please try again later !');
          }

          $('#loading'+post_id).hide();
        }
      });
    }
  };

  var show_more = {
    adjustheight : 102,
    moreText : '+ More',
    lessText : '- Less',
    init: function(){
      $('.list_comment').each(function(index,element){
        if($(element).height() < show_more.adjustheight + 50 ){
          $('#more'+ $(element).attr('rel')).hide();
        }
        show_more.hide($(element).attr('rel'));
      });
      $('.btn-info').live('click',function() {
        var id = $(this).attr('rel');
        if($('#list_comment'+ id).height() > show_more.adjustheight){
          show_more.hide(id);
          $(this).val(show_more.moreText);
        }else{
          show_more.show(id);
          $(this).val(show_more.lessText);
        }
      });
    },
    init_one: function(id,type){
      if(show_more.cal_height(id) < show_more.adjustheight + 50 ){
        $('#more'+ id).hide();
      }else{
        $('#more'+ id).show();
      }

      if(type == 1)
        show_more.hide(id);
    },
    hide: function(id){
      $('#list_comment'+id).animate({
        height: show_more.adjustheight+'px'
      },function() {
        $(this).css('height', show_more.adjustheight).css('overflow', 'hidden');
      });
    },
    show: function(id){
      var totalHeight = show_more.cal_height(id);
      $('#list_comment'+id).animate({
        height: totalHeight + 'px'
      },function() {
        $(this).css('height', 'auto').css('overflow', '');
      });
    },
    cal_height: function(id){
      var totalHeight= 0;
      $('#list_comment'+id).children(".row-fluid").each(function(index,element){
        totalHeight += $(element).height();
      });
      return totalHeight;
    }
  };

  var load_content = {
    page : 1,
    processing : false,
    post_url : '',
    contentPercent : 0.8,
    style : 'user',
    init: function(page,post_url,style){
      if(parseInt(page) > 0 && post_url != ''){
        load_content.page = page;
        load_content.post_url = post_url;
        load_content.style = style;
        load_content.bind_action();
      }
    },
    bind_action: function(){
      $(window).scroll(function(){
        if (load_content.processing)
          return false;

        if ($(window).scrollTop() >= ($(document).height() - $(window).height())*load_content.contentPercent){
          load_content.processing = true; //sets a processing AJAX request flag
          $('#loadingContent').show();
          
          $.ajax({
            type:"POST",
            url:load_content.post_url,
            data:"page=" + load_content.page + "&style=" + load_content.style,
            success:function(res){
              $('#loadingContent').hide();
              if(res.result == 'Success !'){
                load_content.load_html(res.data);
                load_content.page += 1;
                if(res.endPoint == false){
                  setTimeout(function(){load_content.processing = false},3000);
                }
              }else if(res.result == 'Invalid information !'){
                alert('Invalid information !');
              }else{
                alert('Server is busy now. Please try again later !');
              }             
            }
          });

        }

      }); 
    },
    load_html: function(data){
      if(data != null){
        var html = '';
        
        $.each(data, function(index,post){
           html +=  '<div class="row-fluid">' +
                    '<div class="span12 well">' +
                    '<div class="span1">' +
                    '<img class="img-polaroid" width="100%" src="' + post.user_avatar + '" onerror="this.src=\'/data/no-image.jpg\'" alt="' + post.user_username + '">' +
                    '</div>' +
                    '<div class="span11">';
            if(post.user_owner != null){
              html += post.user_owner;
            }

           html +=  '<strong><a href="' + post.user_path + '" target = "_blank">' + post.user_username + '</a></strong><br/>' +
                    '<span id="content_' + post.post_id + '"> ' + post.post_content + '</span>' + 
                    '<div style="clear:both;"></div>' +
                    post.post_date +
                    '</div>' +
                    '<div style="clear:both;"></div>' +
                    '<div id="comment_content' + post.post_id + '">';
            if(post.comments.length > 0){
              html += '<h6>Comment :</h6>' + 
                      '<div id="list_comment' + post.post_id + '" class="list_comment" rel="' + post.post_id + '">';
              $.each(post.comments, function(idx,comment){
                html += '<div class="row-fluid" id="comment'+ comment.comment_id +'">' +
                        '<div class="span12 well" style="background-color: #E6E6E6;margin:0;">' +
                        '<div class="span1">' +
                        '<img src="' + comment.user_avatar + '" onerror="this.src=\'/data/no-image.jpg\'" class="img-polaroid" alt="" />' +
                        '</div>' +
                        '<div class="span11">';
                if(comment.allowDelete == 1){
                  html += '<div class="btn-group" style="float:right;">' +
                          '<button type="button" class="close" data-pid="'+ post.post_id +'" data-cid="'+ comment.comment_id +'" data-url="' + comment.del_path + '" style="color:red;">×</button>' +
                          '</div>';
                }

                html += '<strong><a href="' + comment.user_path + '" target = "_blank">' + comment.user_username + '</a></strong><br/>' +
                        '<span>' + comment.content + '</span>' +
                        '<div style="clear:both;"></div>' +
                        '<i style="float:right;font-size:10px;">( ' + comment.time + ' )</i>' +
                        '</div>' +
                        '</div>' +
                        '</div>';                  
              });
              
              html += '</div>' +
                      '<div style="text-align:right;margin-top: 5px;" id="more' + post.post_id + '" >' +
                      '<input type="button" class="btn btn-info" style="" value="+ More" rel="' + post.post_id + '" />' +
                      '</div>';
            }

            html += '</div>';
            if(post.box_comment != null){
              html += post.box_comment;
            }
            html += '</div></div>';
        });
        
        $(html).insertBefore('#loadingContent');
        
        $.each(data, function(index,post){
          show_more.init_one(post.post_id, 1);
        });
      }
    }
  };
  $(document).ready(function() {
    $('#box_comment').live('keypress',function(e){
      if(e.keyCode == 13){
        $('#loading'+$(this).attr('rel')).show();
        comment_functions.add($(this).attr('imgsrc'),$(this).attr('username'),$(this).attr('userid'),$(this).attr('dest'),$(this).attr('rel'),$(this).val());
        $(this).val('');
        return false;
      }
    });

    $('.close').live('click',function(e){
      if($(this).attr('data-dismiss') == null){
        if(confirm('Do you really want to delete your comment ?')){
          var pid = $(this).attr('data-pid');
          var cid = $(this).attr('data-cid');
          var post_url = $(this).attr('data-url');
          if($.trim(pid) != '' && $.trim(cid) != '' && $.trim(post_url) != ''){
            comment_functions.del($.trim(pid), $.trim(cid), $.trim(post_url));
          }else{
            alert('Invalid information !');
          }
        }
      }
      return false;
    });

    if($('#postUrl').length > 0){
      load_content.init(2,$('#postUrl').val(),$('#curPage').val());
    }

    show_more.init();
  });  
})(jQuery);